package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.vo.Friend;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sort")
@Api(tags = "18、列表排序管理")
@ApiSupport(author = "罗海林", order = 18)
@Validated
public class SortController {

    @PostMapping("/sortObjectList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sortField", value = "排序字段"),
            @ApiImplicitParam(name = "sortType", value = "升降类型")
    })
    @ApiOperation(value = "给对象列表排序", response = Result.class)
    @ApiOperationSupport(author = "罗海林", order = 1)
    public Result sortObjectList(@RequestParam String sortField,
                                 @RequestParam String sortType) {

        List<Friend> friendList = new ArrayList<>();
        friendList.add(new Friend("周罗丹", 35, "2015"));
        friendList.add(new Friend("陈艺文", 39, "2009"));
        friendList.add(new Friend("林春丽", 30, "2021"));

        if (sortType.equals("asc")) {
            if (sortField.equals("name")) {
                friendList = friendList.stream().sorted(Comparator.comparing(Friend::getName)).collect(Collectors.toList());
            }
            else if (sortField.equals("age")) {
                friendList = friendList.stream().sorted(Comparator.comparingInt(Friend::getAge)).collect(Collectors.toList());
            }
            else {
                friendList = friendList.stream().sorted(Comparator.comparing(Friend::getCity)).collect(Collectors.toList());
            }
        }
        else {
            if (sortField.equals("name")) {
                friendList = friendList.stream().sorted(Comparator.comparing(Friend::getName).reversed()).collect(Collectors.toList());
            }
            else if (sortField.equals("age")) {
                friendList = friendList.stream().sorted(Comparator.comparingInt(Friend::getAge).reversed()).collect(Collectors.toList());
            }
            else {
                friendList = friendList.stream().sorted(Comparator.comparing(Friend::getCity).reversed()).collect(Collectors.toList());
            }
        }

        Result res = new Result().ok();
        res.put("result", friendList);
        return res;
    }

}
